<?php
$path = dirname(__FILE__, 2);
$envPath = "$path/.env";
$envExamplePath = "$path/.env.example";
if (file_exists($envPath)) {
    echo ".env is already exists. skipp get config. \n";
    exit;
}
$config_url = getenv('CONFIG_URL');
echo "config is: $config_url \n";
if (!empty($config_url)) {
    $json = file_get_contents(filename: $config_url . 'serve_saas_v1?raw', context: stream_context_create(array(
        'http' => array(
            'header' => 'X-Consul-Token: ' . getenv('CONFIG_KEY'),
        )
    )));
    $arr = @json_decode($json, true);
} else {
    echo "has no CONFIG_URL \n";
    exit;
}
if (empty($arr)) {
    $arr = [];
}

$data = file($envExamplePath, FILE_IGNORE_NEW_LINES);

$data = array_map(function ($line) use ($arr) {

    foreach ($arr as $key => $value) {
        if (str_starts_with($line, $key . "=")) {
            if (ctype_digit($value)) {
                return $key . "=" . $value;
            } elseif (in_array($value, ['null', 'true', 'false'])) {
                return $key . "=$value";
            } else {
                return $key . "=" . '"' . $value . '"';
            }

        }
    }
    return $line;
}, $data);

file_put_contents($envPath, implode(PHP_EOL, $data));
